import base64
import datetime

import jwt


class MyJwt:
    def __init__(self):
        self.SECRET_KEY='asfsf!#$#$@$#^%#$sdfwtwa134342432323fffwf'

    # 加密秘钥 设置过期时间
    def encode_jwt_time(self, userinfo, mytime):
        # 单独控制载荷信息
        playlode = {
            # 设置过期时间
            'exp': int((datetime.datetime.now() + datetime.timedelta(seconds=mytime)).timestamp()),
            'data': userinfo
        }
        mystr = jwt.encode(playlode, self.SECRET_KEY, algorithm="HS256")
        try:
            mystr = str(mystr, 'utf-8')
        except Exception as e:
            pass
        return mystr

    #生成jwt
    def jwt_encode(self,userinfo):
        mystr = jwt.encode(userinfo, self.SECRET_KEY, algorithm="HS256")
        try:
            mystr = str(mystr, 'utf-8')
        except Exception as e:
            pass
        return mystr

    #延长token过期时间 jwt
    def jwt_decode(self,token):
        try:
            data = jwt.decode(token,self.SECRET_KEY,algorthms=['HS256'])
            #重新加密获取新的token
            newtoken = jwt.encode(data,self.SECRET_KEY,algorithm='HS256')
            return str(newtoken)
        except:
            return None
    #对比
    def check(self,token,newtoken):
        if token == newtoken:
            return True
        return False
    # 解密
    def jwt_de(self,token):
        data = jwt.decode(token,self.SECRET_KEY,algorithms='HS256')
        return data
myjwt = MyJwt()

import time

# jt = MyJwt()
# token = myjwt.jwt_encode({'data':{'name':'sdf'}})
# print(token)
#
# newtoken = myjwt.jwt_decode('eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJkYXRhIjp7Im5hbWUiOiJzZGYifX0.29kJRIgSBCf3ArLbzkrVeYC5avkpgUKJGPFUcx3ATYs')

# str = base64.b64encode(newtoken)

# print(myjwt.jwt_de(newtoken))
# flag = myjwt.check(token,newtoken)
# print(flag)
# print(token)
